'''
Adapted from kuangliu/pytorch-cifar .
'''

import torch.nn as nn
import torch
from itertools import combinations
import torch.nn.functional as F


class ChannelAttentionModule(nn.Module):
    def __init__(self, channel, ratio=2):
        super(ChannelAttentionModule, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        # self.max_pool = nn.AdaptiveMaxPool2d(1)

        self.shared_MLP = nn.Sequential(
            nn.Conv2d(channel, channel // ratio, 1, bias=False),
            nn.ReLU(),
            nn.Conv2d(channel // ratio, channel, 1, bias=False)
        )
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avgout = self.shared_MLP(self.avg_pool(x))
        # maxout = self.shared_MLP(self.max_pool(x))
        return self.sigmoid(avgout)


class GLCN(nn.Module):
    def __init__(self, planes=64, n=36):
        """ Constructor
        Args:
            planes: output channel dimensionality.
            n: the number used for channels, default:9*8/2=36
        """
        super(GLCN, self).__init__()
        self.a = [i for i in range(9)]
        self.combination = list(combinations(self.a, 2))
        self.group_conv = nn.Conv2d(2*n, n, kernel_size=1, bias=False, groups=n)
        self.bn_group = nn.BatchNorm2d(n)
        self.relu = nn.ReLU(inplace=True)

        self.conv1 = nn.Conv2d(n, n, kernel_size=1, stride=1, bias=False)
        self.bn1 = nn.BatchNorm2d(n)

        self.channel_attention = ChannelAttentionModule(n)
        self.sigmoid = nn.Sigmoid()
        # self.conv_out = nn.Conv2d(n, planes, kernel_size=1, bias=False)

    def forward(self, x):
        avgout = torch.mean(x, dim=1, keepdim=True)
        x = get_glcm_stack(avgout)

        for (i, (l1, l2)) in enumerate(self.combination):
            fea = torch.cat((x[:, l1, :, :].unsqueeze(dim=1), x[:, l2, :, :].unsqueeze(dim=1)), dim=1)
            if i == 0:
                feas = fea
            else:
                feas = torch.cat((feas, fea), dim=1)
        feas = self.relu(self.bn_group(self.group_conv(feas)))

        feas = self.conv1(feas)
        feas = self.bn1(feas)

        feas = self.channel_attention(feas)*feas
        feas = torch.sum(feas, dim=1).unsqueeze(1)
        return self.sigmoid(feas)


def get_glcm_stack(img, step=1):
    gl3 = torch.cat((img[:, :, :, step:], img[:, :, :, -1 * step:]), dim=3)
    gl6 = torch.cat((img[:, :, step:, :], img[:, :, -1 * step:, :]), dim=2)
    gl7 = torch.cat((img[:, :, :step, :], img[:, :, :-1 * step, :]), dim=2)
    gl8 = torch.cat((img[:, :, :step, :], img[:, :, :-1 * step, :]), dim=2)
    trans_img = torch.cat((img, torch.cat((img[:, :, :, step:], img[:, :, :, -1 * step:]), dim=3), torch.cat((img[:, :, step:, :], img[:, :, -1 * step:, :]), dim=2),
                           torch.cat((gl3[:, :, step:, :], gl3[:, :, -1 * step:, :]), dim=2), torch.cat((img[:, :, :, :step], img[:, :, :, :-1 * step]), dim=3),
                           torch.cat((img[:, :, :step, :], img[:, :, :-1 * step, :]), dim=2), torch.cat((gl6[:, :, :, step:], gl6[:, :, :, -1 * step:]), dim=3),
                           torch.cat((gl7[:, :, :, step:], gl7[:, :, :, -1 * step:]), dim=3), torch.cat((gl8[:, :, :, :step], gl8[:, :, :, :-1 * step]), dim=3)), dim=1)
    return trans_img


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1, stay_conv=False):
        super(BasicBlock, self).__init__()

        self.conv1 = nn.Conv2d(
            in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)

        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.stay_conv = stay_conv

        if self.stay_conv == True:
            self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
                                   stride=1, padding=1, bias=False)
        else:
            self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
                                   stride=1, padding=1, bias=False)
            self.glcn = GLCN()
        # self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
        #                        stride=1, padding=1, bias=False)

        self.bn2 = nn.BatchNorm2d(planes)

        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = self.conv1(x)
        out = self.relu(self.bn1(out))
        if self.stay_conv == True:
            out = self.bn2(self.conv2(out))
        else:
            out = self.bn2(self.conv2(out))
            out = self.glcn(out)*out
        out += self.shortcut(x)
        out = self.relu(out)

        return out


class ResNet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=3):
        super(ResNet, self).__init__()
        self.in_planes = 64
        self.conv1 = nn.Conv2d(1, 64, kernel_size=3,
                               stride=1, padding=1, bias=False)
        # self.glcn = GLCN()
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1, stay_conv=True)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2, stay_conv=True)
        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2, stay_conv=True)
        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2, current_layer=4)

        self.ca = ChannelAttentionModule(ratio=16, channel=512)

        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.linear = nn.Linear(512, num_classes)

    def _make_layer(self, block, planes, num_blocks, stride, stay_conv=False, current_layer=1):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            if current_layer == 4:
                layers.append(block(512, planes, stride, stay_conv=stay_conv))
            else:
                layers.append(block(self.in_planes, planes, stride, stay_conv=stay_conv))
            self.in_planes = planes * block.expansion
        return nn.Sequential(*layers)

    def forward(self, x):
        out = self.conv1(x)
        out = self.relu(self.bn1(out))
        tmp1 = F.interpolate(out, (28, 28))
        out = self.maxpool(out)

        out = self.layer1(out)
        tmp2 = F.interpolate(out, (28, 28))

        out = self.layer2(out)
        tmp3 = F.interpolate(out, (28, 28))

        out = self.layer3(out)
        out = torch.cat((out, tmp1, tmp2, tmp3), dim=1)
        out = self.ca(out)*out

        out = self.layer4(out)

        out = self.avgpool(out)
        out = out.view(out.size(0), -1)
        out = self.linear(out)
        return out


def ResNet18(in_channels, num_classes):
    return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)

if __name__ == '__main__':
    net = ResNet18(1,5)
    input = torch.ones((1,1,224,224))
    out = net(input)
    print(out)